import { reactControl, BaseReactElementControl, ReactViewState, CookieUtil } from "pao-aop-client";
import React from "react";
import { addon } from "pao-aop";
import { Row, Col, Button, Typography, Tree, Modal, message } from "antd";
import { Bed, HotelZone } from "src/projects/models/hotel_zone";
import moment from "moment";
import "./bedStatus.less";
import { GetFieldDecoratorOptions } from "antd/lib/form/Form";
import { AppServiceUtility } from "src/projects/app/appService";
import { request } from "src/business/util_tool";
import { MainContent } from "src/business/components/style-components/main-content";
import FormCreator, { InputType } from "src/business/components/buss-components/form-creator";
import { edit_props_info } from "src/projects/app/util-tool";
import { COOKIE_KEY_CURRENT_USER } from "src/business/mainForm/backstageManageMainForm";
import { User } from "src/business/models/user";

const { Title } = Typography;
const { TreeNode } = Tree;
const titleLevel = 4;
/**
 * 组件：房态图右侧属性状态
 */
export interface BedStatussState extends ReactViewState {
    /** 请假弹窗状态 */
    askforleavestatus?: boolean;
    /** 请假人列表 */
    residents_list?: [];
    /** 床位编号列表 */
    bed_list?: [];
    /** 离开原因列表 */
    leave_reason_list?: [];
    /** 床位id */
    bed_id?: any;
    /** 人员当前状态 */
    status?: string;
    /** 当前id */
    id?: string;
    /** 记录原因 */
    record?: string;
}

/**
 * 组件：房态图右侧属性
 * 描述
 */
export class BedStatuss extends React.Component<BedStatussControl, BedStatussState> {
    constructor(props: any) {
        super(props);
        this.state = {
            bed_list: [],
            residents_list: [],
            leave_reason_list: [],
            bed_id: '',
            status: '离开',
            askforleavestatus: false
        };
    }

    componentDidMount() {
        // 查询床位列表
        request(this, AppServiceUtility.hotel_zone_type_service.get_bed_list!({}))
            .then((datas: any) => {
                this.setState({
                    bed_list: datas.result,
                });
            });
        request(this, AppServiceUtility.check_in_service.get_check_in_list!({}))
            .then((datas: any) => {
                this.setState({
                    residents_list: datas.result,
                });
            });
        // 获取离开原因列表
        request(this, AppServiceUtility.leaveRecord_service.get_leave_reason_list!({}, 1, 999))
            .then((datas: any) => {
                this.setState({
                    leave_reason_list: datas.result,
                });
            });
    }

    /**
     * 计算年龄
     */
    getAge(ageStr: string) {
        /** 实时年份 */
        const year = moment().format('YYYY');
        const residentAge = moment(ageStr).format('YYYY');

        return (parseInt(year, 10) - parseInt(residentAge, 10));
    }
    /** 
     * 查询条件按钮回调
     */
    private button_click = (e: any) => {
        e.click_back!();
    }
    /**
     * 获取床位信息按钮组
     */
    getBedStatusButtonGroup() {
        const { bed_status_arr } = this.props;

        return (
            <Row type={"flex"} gutter={20} justify={"space-around"}>
                {
                    bed_status_arr.map((e, i) =>
                        <Col span={12} key={i}>
                            <Button onClick={() => this.button_click(e)}>
                                <span>●</span>
                                {e.name}
                            </Button>
                        </Col>
                    )
                }
            </Row>
        );
    }

    /**
     * 迭代遍历生成床位位置信息节点
     */
    traversalHotelZoneAndGetHtml(hotelZones: HotelZone[]): any {
        if (!hotelZones || hotelZones.length === 0) {
            return undefined;
        }

        let treeNodeEle: JSX.Element;

        for (let u = hotelZones.length - 1; u >= 0; u--) {
            const e = hotelZones[u];
            treeNodeEle = (
                <TreeNode title={e.zone_name}>
                    {treeNodeEle!}
                </TreeNode>
            );
        }

        return treeNodeEle!;
    }

    /**
     * 获取标题元素
     */
    getTileConTrol(title: string) {
        return (
            <Title level={2}>{title}</Title>
        );
    }

    /**
     * 获取床位信息文字段落
     */
    getBedStatusSection() {
        let { bed_status_info, bed_position_info } = this.props;
        if (!bed_status_info) {
            return undefined;
        }
        const bedInfoEles = [
            (
                <Title key={1} level={titleLevel}>
                    床位编号：{bed_status_info.bed_code}
                </Title>
            ),
            (
                <Title key={2} level={titleLevel}>
                    床位状态：{bed_status_info.residents_id && bed_status_info.residents_id !== '' ? '在住' : '空床'}
                </Title>
            ),
            (
                <Title level={titleLevel}>
                    床位位置：
                    <br />
                    <Tree showIcon={false} checkable={false}>
                        {this.traversalHotelZoneAndGetHtml(bed_position_info!)}
                    </Tree>
                </Title>
            ),
            // TODO: 服务包列表
            // (
            //     <Title level={titleLevel}>
            //         服务包：{resident_info ? this.getAge(resident_info['personnel_info']['date_birth']) : undefined}
            //     </Title>
            // )
        ];

        return (
            <Row >
                {bedInfoEles}
            </Row>
        );
    }
    /**
     * 获取长者信息文字段落
     */
    getElderStatusSection() {
        let { bed_status_info, bed_position_info, resident_info } = this.props;
        if (!bed_status_info) {
            return undefined;
        }
        const bedInfoEles = [
            (
                <Title key={1} level={titleLevel}>
                    床位编号：{bed_status_info.bed_code}
                </Title>
            ),
            (
                <Title key={2} level={titleLevel}>
                    床位状态：{bed_status_info.residents_id && bed_status_info.residents_id !== '' ? '在住' : '空床'}
                </Title>
            ),
            (
                <Title level={titleLevel}>
                    床位位置：
                    <br />
                    <Tree showIcon={false} checkable={false}>
                        {this.traversalHotelZoneAndGetHtml(bed_position_info!)}
                    </Tree>
                </Title>
            ),
            (
                <Title level={titleLevel}>
                    入住长者：{resident_info ? resident_info['name'] : undefined}
                </Title>
            ),
            (

                <Title level={titleLevel}>
                    性别：{resident_info ? resident_info['personnel_info']['sex'] : undefined}
                </Title>
            ),
            (
                <Title level={titleLevel}>
                    年龄：{resident_info ? this.getAge(resident_info['personnel_info']['date_birth']) : undefined}
                </Title>
            ),
            (
                <Title level={titleLevel}>
                    证件号：{resident_info ? resident_info['id_card'] : undefined}
                </Title>
            ),
            (
                <Title level={titleLevel}>
                    联系方式：{resident_info ? resident_info['personnel_info']['telephone'] : undefined}
                </Title>
            ),
        ];

        return (
            <Row >
                {bedInfoEles}
            </Row>
        );
    }
    askforleave() {
        if (!this.props.resident_info) {
            message.error('请选择用户！');
            return;
        }
        this.setState({ askforleavestatus: !this.state.askforleavestatus }, () => {
            request(this, AppServiceUtility.check_in_service.get_check_in_list!({ "user_id": this.props.resident_info.id }, 1, 1))
                .then((datas: any) => {
                    if (datas.result.length > 0) {
                        this.setState({
                            bed_id: datas.result[0].bed_id[0]
                        });
                        request(this, AppServiceUtility.leaveRecord_service.get_leave_list!({ "residents_id": datas.result[0].user_id }))
                            .then((datas: any) => {
                                if (datas.result.length > 0) {
                                    if (datas.result[0].status === '入住') {
                                        this.setState({
                                            status: datas.result[0].status,
                                            id: datas.result[0].id,
                                            record: datas.result[0].record,
                                        });
                                    }
                                }
                            });
                    }
                });
        });
    }
    handlecancel() {
        this.setState({
            askforleavestatus: false
        });
    }
    render() {
        const bedStatusButtonGroup = this.getBedStatusButtonGroup();
        const bedStatusSection = this.getBedStatusSection();
        const elderStatusSection = this.getElderStatusSection();

        let bed = this.state.bed_list;
        let bed_list: any[] = [];
        bed!.map((item, idx) => {
            bed_list.push(<option key={item['id']}>{item['bed_code']}</option>);
        });
        let residents_list: any[] = [];
        this.state.residents_list!.map((item, idx) => {
            residents_list.push(<option key={item['user_id']}>{item['name']}</option>);
        });
        let leave_reason = this.state.leave_reason_list;
        let leave_reason_list: any[] = [];
        leave_reason!.map((item, idx) => {
            leave_reason_list.push(<option key={item['id']}>{item['name']}</option>);
        });
        let operation_personnel_name = CookieUtil.read<User>(COOKIE_KEY_CURRENT_USER) && CookieUtil.read<User>(COOKIE_KEY_CURRENT_USER).name ? CookieUtil.read<User>(COOKIE_KEY_CURRENT_USER).name : '...';
        let leave_mes = {
            title: "离开信息",
            need_card: true,
            input_props: [
                // {
                //     type: InputType.date,
                //     label: "离开时间",
                //     decorator_id: "checkout_date",
                //     field_decorator_option: {
                //         rules: [{ required: true, message: "请输入离开时间" }],
                //         initialValue: moment(now_date),
                //     } as GetFieldDecoratorOptions,
                //     option: {
                //         placeholder: "请输入离开时间",
                //         disabled: true,
                //         // value: moment().format("YYYY-MM-DD HH:mm:ss") // 当前时间
                //     }
                // },
                {
                    type: InputType.antd_input,
                    label: "接出人",
                    decorator_id: "pickout_id",
                    field_decorator_option: {
                        rules: [{ message: "请输入接出人" }],
                    } as GetFieldDecoratorOptions,
                    option: {
                        placeholder: "请输入接出人",
                        disabled: false,
                    }
                }, {
                    type: InputType.antd_input,
                    label: "操作人员",
                    decorator_id: "operating_personnel_id2",
                    field_decorator_option: {
                        // rules: [{ message: "请选择操作人员" }],
                        initialValue: operation_personnel_name,
                    } as GetFieldDecoratorOptions,
                    option: {
                        placeholder: "操作人员",
                        // childrens: residents_list,
                        disabled: true,
                    }
                },
            ],
        };

        let check_in = {
            title: "入住信息",
            need_card: true,
            input_props: [
                // {
                //     type: InputType.date,
                //     label: "入住时间",
                //     decorator_id: "checkin_date",
                //     field_decorator_option: {
                //         rules: [{ required: true, message: "请输入入住时间" }],
                //     } as GetFieldDecoratorOptions,
                //     option: {
                //         placeholder: "请输入入住时间",
                //         // childrens: service_bakage_list
                //         disabled: false,
                //         value: moment().format("YYYY-MM-DD HH:mm:ss") // 当前时间
                //     }
                // }, 
                {
                    type: InputType.antd_input,
                    label: "送入人",
                    decorator_id: "enter_id",
                    field_decorator_option: {
                        rules: [{ required: true, message: "请输入送入人" }],
                    } as GetFieldDecoratorOptions,
                    option: {
                        placeholder: "请输入送入人",
                        disabled: false
                    }
                }, {
                    type: InputType.antd_input,
                    label: "操作人员",
                    decorator_id: "operating_personnel_id3",
                    field_decorator_option: {
                        // rules: [{ message: "请选择操作人员" }],
                        initialValue: operation_personnel_name,
                    } as GetFieldDecoratorOptions,
                    option: {
                        placeholder: "操作人员",
                        // modal_search_items_props: modal_search_items_props4,
                        disabled: true
                    }
                },
            ],
        };
        let edit_props = {
            form_items_props: [
                {
                    title: "长者信息",
                    need_card: true,
                    input_props: [
                        {
                            type: InputType.select,
                            label: "请假人",
                            decorator_id: "residents_id",
                            field_decorator_option: {
                                initialValue: this.props.resident_info ? this.props.resident_info.id : '',
                            } as GetFieldDecoratorOptions,
                            option: {
                                childrens: residents_list,
                                disabled: true,
                            }
                        }, {
                            type: InputType.select,
                            label: "床位编号",
                            decorator_id: "bed_id",
                            field_decorator_option: {
                                rules: [{ required: true, message: "请输入床位编号" }],
                                initialValue: this.state.bed_id ? this.state.bed_id : '',
                            } as GetFieldDecoratorOptions,
                            option: {
                                placeholder: "请输入床位编号",
                                childrens: bed_list,
                                disabled: true,
                            }
                        },
                        {
                            type: InputType.antd_input,
                            label: "状态",
                            decorator_id: "status",
                            field_decorator_option: {
                                initialValue: this.state.status ? this.state.status : '',
                            } as GetFieldDecoratorOptions,
                            option: {
                                disabled: true,
                            }
                        },
                    ],
                },
                {
                    title: "记录登记",
                    need_card: true,
                    input_props: [
                        {
                            type: InputType.select,
                            label: "记录原因",
                            decorator_id: "record_reason_id",
                            field_decorator_option: {
                                rules: [{ required: true, message: "请选择记录原因" }],
                            } as GetFieldDecoratorOptions,
                            option: {
                                placeholder: "请选择记录原因",
                                childrens: leave_reason_list,
                                disabled: false,
                            }
                        },
                        //  {
                        //     type: InputType.date,
                        //     label: "申请时间",
                        //     decorator_id: "apply_date",
                        //     field_decorator_option: {
                        //         rules: [{ required: true, message: "请输入申请时间" }],
                        //     } as GetFieldDecoratorOptions,
                        //     option: {
                        //         placeholder: "请输入申请时间",
                        //         disabled: false,
                        //         value: moment().format("YYYY-MM-DD HH:mm:ss") // 当前时间
                        //     }
                        // }, 
                        {
                            type: InputType.text_area,
                            label: "记录说明",
                            decorator_id: "record",
                            field_decorator_option: {
                                rules: [{ message: "请输入记录说明" }],
                                initialValue: this.state.record ? this.state.record : '',
                            } as GetFieldDecoratorOptions,
                            option: {
                                placeholder: "请输入记录说明",
                                disabled: false,
                            }
                        },
                    ]
                },
            ],
            other_btn_propps: [
                {
                    text: "关闭",
                    cb: () => {
                        console.log("返回回调");
                        this.setState({
                            askforleavestatus: false
                        });
                    }
                }
            ],
            submit_btn_propps: {
                text: "保存"
            },
            service_option: {
                service_object: AppServiceUtility.leaveRecord_service,
                operation_option: {
                    query: {
                        func_name: "get_leave_list_all",
                        arguments: [{ id: this.state.id }, 1, 1]
                    },
                    save: {
                        func_name: "update_leave_record"
                    }
                },
            },
            succ_func: () => { this.setState({ askforleavestatus: false }); },
            id: this.state.id,
        };
        let edit_props_list = Object.assign(edit_props, edit_props_info);
        if (this.state.status === '入住') {
            edit_props_list.form_items_props.push(leave_mes);
        }
        if (this.state.status === '离开') {
            edit_props_list.form_items_props.push(check_in);
        }
        return (
            (
                <Row className={'bed-status-row'}>
                    <Row>
                        <Row>
                            {this.getTileConTrol("筛选条件")}
                            {bedStatusButtonGroup}
                        </Row>
                        {
                            this.props.resident_info ? (
                                <Row>
                                    {this.getTileConTrol("长者信息")}
                                    {elderStatusSection}
                                </Row>
                            ) : (
                                    <Row>
                                        {this.props.bed_status_info ? this.getTileConTrol("床位信息") : undefined}
                                        {bedStatusSection}
                                    </Row>
                                )

                        }
                    </Row>
                    {
                        this.props.resident_info ? (
                            <Row className={"router-btn"}>
                                <Col span={24}>
                                    <Button onClick={this.askforleave = this.askforleave.bind(this)}>
                                        请假销假
                                    </Button>
                                    <Modal
                                        title="请假销假"
                                        visible={this.state.askforleavestatus}
                                        width={1000}
                                        footer={null}
                                        onCancel={this.handlecancel = this.handlecancel.bind(this)}
                                        destroyOnClose={true}
                                    >
                                        <div className="formcreator">
                                            <MainContent>
                                                <FormCreator {...edit_props_list} />
                                            </MainContent>
                                        </div>
                                    </Modal>
                                </Col>
                                {/* <Col span={24}>
                                    <Button>
                                        住宿记录
                                    </Button>
                                </Col> */}
                                <Col span={24}>
                                    <Button onClick={this.props.retreat}>
                                        办理退住
                            </Button>
                                </Col>
                            </Row>
                        ) :
                            null
                    }

                </Row>
            )
        );
    }
}

/**
 * 控件：房态图右侧属性控制器
 * 描述
 */
@addon('BedStatuss', '房态图', '房态图')
@reactControl(BedStatuss, true)
export class BedStatussControl extends BaseReactElementControl {
    bed_status_arr: {
        name: string;
        color?: string;
        click_back?: any;
    }[];

    bed_status_info: Bed;

    bed_position_info: HotelZone[];

    resident_info: any;
    /** 退住按钮回调 */
    retreat?: React.MouseEventHandler<HTMLElement>;
}